var express = require('express');
var router = express.Router();
var md5 = require("md5");
// 数据库
var userDAO = require("../bin/cn/userDAO.js");
// 导入时间函数
var newtime = require("../bin/libs/time.js");
// 判断是否登录
var isLogin = require("../bin/libs/isLogin.js");


// 配置邮件,用于发送电子邮件协议
var nodemailer = require('nodemailer')
var smtpTransport = require('nodemailer-smtp-transport');
// 邮箱和随机数
var config = require('../bin/libs/config.js')
var strRandom = require('../bin/libs/strRandom.js')

var mailSender = nodemailer.createTransport(smtpTransport({
	service:config.email.service,
	auth:{
		user:config.email.user,
		pass:config.email.pass,
	}
}))


/* 注册*/
router.get('/regist', function(req, res, next) {
  var sj = newtime();
  var psw = md5(req.query.psw);
  var obj = {
    name:req.query.name,
    email:req.query.email,
    psw:psw,
    time:sj,
  }
  // console.log(obj);
  userDAO.findOne({email:req.query.email})
  .then(data=>{
    if(data){
      res.json({err:1,msg:"邮箱已经存在"});
    }else{
      var u = new userDAO(obj);
      u.save()
      .then(datas=>{
        req.session.user = datas;
        res.json({err:0,msg:"注册成功"});
      })
    }
  })
});

// 登录
router.post("/login",(req,res)=>{
  // console.log(req.body);
  var psw = md5(req.body.psw);
  var obj = {
    email:req.body.email,
    psw:psw,
  }
  userDAO.findOne(obj)
  .then(data=>{
    if(data){
      req.session.user = data;
      res.json({err:0,msg:"登录成功"});
    }else{
      res.json({err:1,msg:"邮箱或密码错误"});
    }
  })

})

// 检查是否已经登录
router.get("/isLogin",(req,res)=>{
  if(req.session.user){
    res.json({err:0});
  }else{
    res.json({err:1});    
  }
});

// 退出登录
router.get('/exit',(req,res)=>{
  delete req.session.user;
  res.json({err:0});
});

// 查看个人信息
router.get("/setting",isLogin)
router.get("/setting",(req,res)=>{
  userDAO.findOne({_id:req.session.user._id})
  .then(data=>{
    res.json({err:0,data:data});
  })
});

// 修改个人信息
router.post("/setting",isLogin)
router.post("/setting",(req,res)=>{
  userDAO.findOne({_id:req.session.user._id})
  .then(data=>{
    data.name = req.body.name;
    data.introduce = req.body.introduce;
    var d = new userDAO(data);
    d.save()
    .then(d=>{
      req.session.user = d;
      res.json({err:0,data:d});
    })
  })
});


// 导入文件上传模块
var multer = require("multer");
var storage = multer.diskStorage({
    destination: function (req,file,cb) {
        cb(null,'./public/img/avatar');
    },
    filename: function (req,file,cb) {
        var suffix = file.mimetype.split("/")[1];
        var namr = file.fieldname + '-'+Date.now()+'.'+suffix;
        cb(null,namr);
        req.arr="/img/avatar/"+namr;
    }
})
var upload = multer({storage: storage});

// 上传头像
var fs = require("fs");
router.post("/avatar",isLogin);
router.post("/avatar",upload.single("avatar"),(req,res)=>{
  var aaaaaa = req.session.user.avatar;
  req.session.user.avatar = req.arr;
  userDAO.update({_id:req.session.user._id},{$set:{
    avatar:req.arr
  }})
  .then(data=>{
    res.json({err:0,msg:"上传成功"});
    if(aaaaaa){
      fs.unlinkSync("./public"+aaaaaa);
    }
  })
});

// 发送邮件找回密码
router.get("/captcha",(req,res)=>{
  if(!req.session.captcha){
    res.json({err:3,msg:"验证码过期或失效"});
    return;
  }
  if(req.session.captcha.toLocaleUpperCase()!=req.query.captcha.toLocaleUpperCase()){
    req.session.captcha="";
    res.json({err:1,msg:"验证码错误"});
    return;
  }
  userDAO.findOne({email:req.query.email})
  .then(data=>{
    req.session.captcha="";
    if(!data){
      res.json({err:2,msg:"此邮箱没有注册"});
    }else{
      var num = strRandom(10);
      userDAO.update({email:req.query.email},{$set:{code:num}})
      .then(()=>{
          mailSender.sendMail({
          // 发送者
          from:config.email.user,
          to:req.query.email,

          subject:"验证邮件",
          html:`
          <h1>验证邮件</h1>
          <p>请点击下面地址验证邮件</p>
          <a href="http://localhost:8080/#/users/auth/${num}">http://localhost:8080/#/users/auth/${num}</a>
          `
        },function(err){
          if(err){
            console.log("邮件发送失败");
            res.json({err:4,msg:"邮件发送失败"});
          }else{
            console.log("邮件发送成功");
            res.json({err:0,msg:"邮件已经发送您的邮箱"});
          }
        })
      })
    }
  })
})

// 找回密码
router.post("/captcha",(req,res)=>{
  userDAO.findOne({code:req.body.code})
  .then(data=>{
    if(req.body.yz){
      if(data){
        res.json({err:3,msg:"存在"});
        return
      }else{
        res.json({err:2,msg:"不存在"});
        return;
      }
    }
    if(data){
      if(!req.body.psw){
        req.body.psw="555";
      }
      data.psw = md5(req.body.psw);
      data.code = "";
      data.save()
      .then(data=>{
        res.json({err:0,msg:"更改成功"});
      })
    }else{
      res.json({err:1,msg:"已经过期"});
    }
  })
});

// 更换密码
router.get("/psw",isLogin)
router.get("/psw",(req,res)=>{
  var reg = /^\w{3,18}$/;
  if(!reg.test(req.query.psw)){
    res.json({err:2,msg:"密码是3-18位"});
    return;
  }
  userDAO.findOne({_id:req.session.user._id})
  .then(data=>{
    if(data.psw==md5(req.query.psw1)){
      data.psw=md5(req.query.psw2);
      data.save()
      .then(datas=>{
        req.session.user = datas;
        res.json({err:0,msg:"修改成功"});      
      })
    }else{
      res.json({err:1,msg:"原密码输入错误"});      
    }
  })
})

// 关注
router.get("/info",isLogin)
router.get("/info",(req,res)=>{
  userDAO.findOne({_id:req.session.user._id})
  .then(data=>{
    if(data.info.indexOf(req.query.info)==-1){
      data.info.push(req.query.info)
    }
    data.save()
    .then(datas=>{
      req.session.user = datas;
      userDAO.findOne({_id:req.query.info})
      .then(data2=>{
        if(data2.fans.indexOf(datas._id)==-1){
          data2.fans.push(datas._id)
        }
        data2.save();
      })
      res.json({err:0,msg:"关注成功"});
    })
  })
});

// 取消关注
router.post("/info",isLogin)
router.post("/info",(req,res)=>{
  userDAO.findOne({_id:req.session.user._id})
  .then(data=>{
    if(data.info.indexOf(req.body.info)>-1){
      data.info.splice(data.info.indexOf(req.body.info),1);
    }
    data.save()
    .then(datas=>{
      req.session.user = datas;
      userDAO.findOne({_id:req.body.info})
      .then(data2=>{
        if(data2.fans.indexOf(datas._id)>-1){
          data2.fans.splice(data.info.indexOf(datas._id),1);
        }
        data2.save();
      })
      res.json({err:0,msg:"取消关注成功"});
    })
  })
});

// 我的关注
router.get("/fen",isLogin);
router.get("/fen",(req,res)=>{
  userDAO.findOne({_id:req.session.user._id})
  .populate("info")
  .populate("fans")
  .then(data=>{
    res.json({err:0,data:data});
  })
})

module.exports = router;
